using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Blog.IService;
using Blog.Command;
using Blog.Model;
using Blog.Model.DTO;
using Blog.Command.Utility;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;

namespace Blog.WebApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize]
    public class UserControllers : ControllerBase
    {
        private readonly IWriterInfoService _iwriterInfoService;

        public UserControllers(IWriterInfoService iwriterInfoService)
        {
            _iwriterInfoService = iwriterInfoService;
        }

        [HttpGet]
        public async Task<ActionResult> QueryAsync()
        {
            var data = await _iwriterInfoService.QueryAsync();
            return Ok(data);
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<ApiResult> CreateAsync(string name, string Username, string Password)
        {
            WriterInfo wirter = new()
            {
                Name = name,
                UserName = Username,
                UserPwd = MD5Helper.MD5Encrypt32(Password),
            };

            //数据校验
            var oldName = await _iwriterInfoService.FindAsync(c => c.UserName == Username);
            if (oldName != null)
                return ApiResultHelper.Error("账号已存在");
            bool bl = await _iwriterInfoService.CreateAsync(wirter);
            if(!bl)
                return ApiResultHelper.Error("添加失败");
            return ApiResultHelper.Success("添加成功");
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<ApiResult> FindAsync([FromServices]IMapper iMapper, int id)
        {
            var writer = await _iwriterInfoService.FindAsync(id);
            var WriterDTO = iMapper.Map<WriterDTO>(writer);
            return ApiResultHelper.Success(WriterDTO);
        }

        [HttpPut]
        public async Task<ApiResult> EditAsync(string OldName, string Newname)
        {
            //int id = Convert.ToInt32(this.User.FindFirst("Id").Value);
            //var writer = await _iwriterInfoService.FindAsync(id);
            var writer = await _iwriterInfoService.FindAsync(c => c.Name == OldName);
            writer.Name = Newname;
            bool bl = await _iwriterInfoService.EditAsync(writer);
            if (!bl)
                return ApiResultHelper.Error("更新数据失败");
            return ApiResultHelper.Success("数据更新成功");
        }
    }
}